package edu.jsnu.service.ticket.schedule.service.impl;

import beans.PageQuery;
import com.github.pagehelper.PageHelper;
import edu.jsnu.service.ticket.schedule.dao.ScheduleMapper;
import edu.jsnu.service.ticket.schedule.domain.Schedule;
import edu.jsnu.service.ticket.schedule.dto.ScheduleShow;
import edu.jsnu.service.ticket.schedule.service.ScheduleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ScheduleServiceImpl implements ScheduleService {

    @Autowired
    private ScheduleMapper scheduleMapper;

    @Override
    public List<ScheduleShow> getSchedule(PageQuery pageQuery) {
        PageHelper.startPage(pageQuery.getPage(), pageQuery.getLimit());
        List<ScheduleShow> scheduleList = scheduleMapper.getSchedule();
        return scheduleList;
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    @Override
    public String getFilmTypesetting(Schedule schedule, boolean flag) {
        //时间格式化到分钟，不需要秒
        try {
            schedule.setStartTime(sdf.parse(sdf.format(schedule.getStartTime())));
            schedule.setEndTime(sdf.parse(sdf.format(schedule.getEndTime())));
        } catch (ParseException e) {
            System.out.println("日期转换异常");
        }
        boolean isSuccess = false;
        //status = 1，表示影片未开始
        schedule.setStatus(1);
        List<Schedule> scheduleList = new ArrayList<>();
        List<Schedule> scheduleRepeat = new ArrayList<>();
        //取得与前台传回的日期list
        scheduleList = scheduleMapper.getScheduleByPlace(schedule.getPlace(), new SimpleDateFormat("yyyy-MM-dd").format(schedule.getStartTime()));
        if (!scheduleList.isEmpty()) {
            if (flag) {
                for (Schedule s : scheduleList) {
                    //首先判断此链表是否有重复时间段
                    if ((schedule.getStartTime().getTime() > s.getStartTime().getTime() && schedule.getStartTime().getTime() < s.getEndTime().getTime() || (schedule.getEndTime().getTime() > s.getStartTime().getTime() && schedule.getEndTime().getTime() < s.getEndTime().getTime()))) {
                        scheduleRepeat.add(s);
                    }
                }
                //如果有
                if (!scheduleRepeat.isEmpty()) {
                    int[] ids = new int[scheduleRepeat.size()];
                    for (int i = 0; i < scheduleRepeat.size(); i++) {
                        ids[i] = scheduleRepeat.get(i).getId();
                    }
                    scheduleMapper.deleteByScheduleIds(ids);//从数据库删除
                }
                //如果为true，强制设置时间
                scheduleMapper.insert(schedule);
                //获取最新排片list
                scheduleList = scheduleMapper.getScheduleByPlace(schedule.getPlace(), new SimpleDateFormat("yyyy-MM-dd").format(schedule.getStartTime()));
                //重新写入刚记录的Schedule对象
                Schedule[] scheduleArr = new Schedule[scheduleRepeat.size()];
                scheduleRepeat.toArray(scheduleArr);
                isSuccess = setMostWellFilmTime(scheduleList, scheduleArr);
            } else {
                isSuccess = setMostWellFilmTime(scheduleList, schedule);
            }
        } else {
            //无排片信息。直接写入
            scheduleMapper.insert(schedule);
            return "添加成功";
        }
        if (isSuccess){
            return "添加成功";
        }else{
            return "添加失败";
        }
    }

    @Override
    public ScheduleShow getScheduleById(Integer scheduleId) {
        return scheduleMapper.getScheduleInfo(scheduleId);
    }

    @Override
    public Integer batchDel(Integer[] ids) {
        Map<String, Integer[]> map = new HashMap<>();
        map.put("ids", ids);
        Integer result = scheduleMapper.batchDel(map);
        return result;
    }

    @Override
    public int updateByPrimaryKeySelective(Schedule schedule) {
        return scheduleMapper.updateByPrimaryKeySelective(schedule);
    }

    @Override
    public Integer deleteScheduleById(Integer id) {
        Integer result = scheduleMapper.deleteByPrimaryKey(id);
        return result;
    }

    private final long fixedTime = 30 * 60 * 1000;//30分钟间隔
    public boolean setMostWellFilmTime(List<Schedule> sList, Schedule... sWrt) {
        //当天最早开始时间，当天最晚结束时间
        Date firstSchedule = null, lastSchedule = null;
        long filmTimes = 0;
        for (int i = 0; i < sWrt.length; i++) {
            //执行一次的条件
            boolean onceFlag = true;
            try {
                if (i == 0) {
                    firstSchedule = sdf.parse(new SimpleDateFormat("yyyy-MM-dd").format(sWrt[i].getStartTime()) + " 08:00");
                    lastSchedule = sdf.parse(new SimpleDateFormat("yyyy-MM-dd").format(sWrt[i].getStartTime()) + " 23:00");
                }
            } catch (ParseException e) {
                System.out.println("时间转换错误！");
            }
            Schedule s = sWrt[i];
            //是否找到合适的位置的标志
            boolean flag = false;
            //是否为最后一条的标志
            boolean isLast = false;
            filmTimes = s.getEndTime().getTime() - s.getStartTime().getTime();
            for (int j = 0; j < sList.size(); j++) {
                //数据库就一条记录的话
                if (sList.size() == 1) {
                    if (sList.get(j).getStartTime().getTime() - firstSchedule.getTime() > filmTimes + fixedTime) {
                        s.setStartTime(firstSchedule);
                        s.setEndTime(new Date(firstSchedule.getTime() + filmTimes));
                    } else {
                        //否则放到最后
                        isLast = true;
                    }
                    flag = true;
                } else {
                    //数据库有多条记录，判断是否为最后一条记录
                    if (sList.size() - 1 == j) {
                        isLast = true;
                        flag = true;
                    } else {
                        if (onceFlag) {
                            if (sList.get(j).getStartTime().getTime() - firstSchedule.getTime() > filmTimes + fixedTime) {
                                s.setStartTime(firstSchedule);
                                s.setEndTime(new Date(firstSchedule.getTime() + filmTimes));
                                flag = true;
                            }
                            onceFlag = false;
                        }
                        if (sList.get(j + 1).getStartTime().getTime() - sList.get(j).getEndTime().getTime() > filmTimes + fixedTime) {
                            s.setStartTime(new Date(sList.get(j).getEndTime().getTime() + fixedTime));
                            s.setEndTime(new Date(s.getStartTime().getTime() + filmTimes));
                            flag = true;
                        }
                    }
                }
                if (isLast) {
                    //如果写到最后，查看当天时间最后时间是否允许,默认23:00为当天最后一场
                    if (lastSchedule.getTime() - sList.get(j).getEndTime().getTime() > fixedTime + filmTimes){
                        s.setStartTime(new Date(sList.get(j).getEndTime().getTime() + fixedTime));
                        s.setEndTime(new Date(s.getStartTime().getTime() + filmTimes));
                    }else {
                        return false;
                    }
                }
                if (flag) {
                    scheduleMapper.insert(s);
                    sList = scheduleMapper.getScheduleByPlaceId(s.getPlace(), new SimpleDateFormat("yyyy-MM-dd").format(s.getStartTime()));
                    break;
                }
            }
        }
        return true;
    }



}
